<template>
  <el-menu
    ref="elMenu"
    :default-active="activeMenu"
    :router="router"
    v-bind="$attrs"
    :default-openeds="opened"
    class="el-menu-vertical-demo"
    :text-color="'rgba(255, 255, 255, 0.65)'"
    :background-color="'#48a5e8'"
    :active-text-color="'#ffffff'"
  >
    <template v-for="(item, index) in data" :key="index">
      <el-menu-item v-if="!item.children || !item.children.length" :index="item.index">
        <el-icon v-if="item.icon">
          <component :is="item.icon"></component>
        </el-icon>
        <span>{{ item.name }}</span>
      </el-menu-item>

      <el-sub-menu v-if="item.children && item.children.length" :index="item.index">
        <template #title>
          <el-icon v-if="item.icon">
            <component :is="item.icon"></component>
          </el-icon>
          <span :class="isActive(item.index)">{{ item.name }}</span>
        </template>
        <el-menu-item v-for="(item1, index1) in item.children" :key="index1" :index="item1.index">
          <el-icon v-if="item1.icon">
            <component :is="item1.icon"></component>
          </el-icon>
          <span class="hover1">{{ item1.name }}</span>
        </el-menu-item>
      </el-sub-menu>
    </template>
  </el-menu>
</template>

<script lang="ts" setup>
import { useRouter, useRoute } from 'vue-router';
import { PropType, watch, ref, reactive } from 'vue';
import { MenuItem } from './types';
const router = useRouter();
const route = useRoute();
let props = defineProps({
  data: {
    type: Array as PropType<MenuItem[]>,
    required: true,
  },
  // 默认选中菜单
  defaultActive: {
    type: String,
    default: '',
  },
  // 是否是路由模式
  router: {
    type: Boolean,
    default: false,
  },
});

// const activeMenu = computed(() => {
//   const { meta, path } = route;
//   console.log(meta, path);
//   if (meta.activeMenu) {
//     console.log();
//     return meta.activeMenu;
//   }
//   return path;
// });
const activeMenu = ref('');
let opened = reactive<string[]>([]);
//el-menu 标签中设置 :default-active="onRoutes"
watch(
  () => router.currentRoute.value,
  (newValue, oldValue) => {
    opened = [];
    const { meta, path } = route;
    opened.push(location.pathname);
    if (newValue.meta.isSingle) {
      activeMenu.value = newValue.meta.activeMenu as string;
    } else {
      activeMenu.value = newValue.path;
    }
  },

  { immediate: true }
);

const isActive = (index: string) => {
  return {
    'text-white': opened.includes(index),
  };
};
</script>

<style scoped>
.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
  min-height: 400px;
}
</style>
<style>
.el-menu-item.is-active {
  background: rgb(61 143 200);
}
.lewUFY {
  color: rgba(255, 255, 255, 0.65);
}
.hover1:hover {
  color: #ffffff;
}
</style>
